#!/bin/bash
set -e

while getopts  ":s:t:h" opts
do
	case  $opts  in
	s)
		sample_name=$OPTARG
		;;
	t)
		type=$OPTARG
	;;
	h)
		echo `basename $0` "[-s sample_name] [-t snp|cnv] file"
		exit 1
		;;
	\?)
		
		echo `basename $0`': invalid option'
		exit 1
		;;
	esac
done
shift $(($OPTIND - 1))

if [ -z "$1" ]; then
	echo `basename $0` "[-s sample_name] [-t snp|cnv] file"
	exit 1
fi

if [ -z "$type" ]; then
	type=cnv;
	dest_sub=.cnvsc
elif test "$type" = "cnv"; then
	dest_sub=.cnvsc
elif test "$type" = "snp"; then
	dest_sub=.snp
elif test "$type" = "tes"; then
	dest_sub=.tes
else
	echo `basename $0`': invalid option'
	exit 1
fi

. /mnt/ilustre/app/medical/tools/.var

dir0=$(pwd |awk -F'/' '{print $NF}')
dir=$dest/$dest_sub/$dir0

if test ! -d $dir; then
mkdir $dir
# chmod 775 $dir
fi

cp -r --backup=numbered --preserve=timestamps -t $dir $@

# for file in $(ls -A $dir); do
# if test -d $file; then
# chmod -R 770 $dir/$file
# else
# chmod 660 $dir/$file
# fi
# done

list=$dest/$dest_sub/.list

if test -e $list; then
	cut -f1 $list >list1
	dir1=^$dir0$
	if grep $dir1 list1; then
		rm list1
	else
		rm list1
		echo -e $dir0'\t'`date -r $( ls -1t |sed -n '1p') +%s`'\t'`pwd` >> $dest/$dest_sub/.list
	fi
	
else
	echo -e $dir0'\t'`date -r $( ls -1t |sed -n '1p') +%s`'\t'`pwd` >> $dest/$dest_sub/.list
fi

cd $dest/$dest_sub
cat $dest/$dest_sub/.list |sort -r -k2 |format_html_index.pl -n$type |cat $tools_path/html/header.html - $tools_path/html/footer.html > $dest/$dest_sub/index.html